package com.yf.utils;

import lombok.extern.log4j.Log4j2;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.InputStream;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

@Log4j2
public class WxXmlParser extends DefaultHandler {
    Deque<String> stack;
    Map<String, String> params;

    public Map<String, String> getParams() {
        return params;
    }

    public WxXmlParser() {
        stack = new LinkedList<>();
        params = new HashMap<>(4);
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String name = stack.peek();
        String s = String.valueOf(ch, start, length);
        if (name != null) {
            params.put(name, s);
        }
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        stack.push(qName);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        stack.pop();
    }

    public static Map<String, String> parseWxTxtContent(InputStream is) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            WxXmlParser wxXmlParser = new WxXmlParser();
            parser.parse(is, wxXmlParser);
            return wxXmlParser.getParams();
        } catch (Exception ignore) {
            log.error(ignore.getMessage());
        }
        return null;
    }
}
